package com.videoanalysis.config;

import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;

@Data
public class AppConfig {
    private static final Logger logger = LoggerFactory.getLogger(AppConfig.class);
    private static AppConfig instance;

    private FFmpegConfig ffmpeg;
    private TencentCloudConfig tencentCloud;
    private OutputConfig output;
    private RecognitionConfig recognition;

    @Data
    public static class RecognitionConfig {
        private String type = "tencent"; // 默认使用腾讯云识别器
        private LocalConfig local;
        private int maxResults = 5; // 每张图片返回的最大识别结果数

        @Data
        public static class LocalConfig {
            private boolean detectFaces = true;
            private boolean analyzeColors = true;
            private boolean detectEdges = true;
        }
    }

    @Data
    public static class OutputConfig {
        private String directory;
    }

    @Data
    public static class FFmpegConfig {
        private String path;
        private int frameIntervalSeconds = 2; // 默认每2秒提取一帧
    }

    @Data
    public static class TencentConfig {
        private String secretId;
        private String secretKey;
    }

    @Data
    public static class TencentCloudConfig {
        private String region;
        private String endpoint;
        private Credentials credentials;
        private Recognition recognition;

        @Data
        public static class Credentials {
            private String secretIdEnv;
            private String secretKeyEnv;
            private String secretId;
            private String secretKey;
        }

        @Data
        public static class Recognition {
            private int maxResults;
        }
    }

    public static AppConfig getInstance() {
        if (instance == null) {
            synchronized (AppConfig.class) {
                if (instance == null) {
                    instance = loadConfig();
                }
            }
        }
        return instance;
    }

    private static AppConfig loadConfig() {
        try (InputStream input = AppConfig.class.getClassLoader().getResourceAsStream("app.yaml")) {
            if (input == null) {
                logger.error("Unable to find app.yaml");
                throw new RuntimeException("Unable to find app.yaml");
            }

            Yaml yaml = new Yaml();
            return yaml.loadAs(input, AppConfig.class);
        } catch (Exception e) {
            logger.error("Error loading configuration", e);
            throw new RuntimeException("Error loading configuration", e);
        }
    }
}
